class Admin::GoodsController < ApplicationController
  layout 'studio'
  before_action :set_good, only: [:show, :edit, :update, :destroy, :record, :change_status, :price]
  before_action :authorize_good, except: [:goods_shop]
  before_action :authorize_save, only:[:new,:create]

  def index
    @sale_courses = SaleCourse.where(company_id: nil)
    @sale_courses +=  current_company.sale_courses
    #@goods_categories = current_company.goods_category_configurations

    params[:good_type] ||= "all"
    params[:good_info_id] ||= "all"
    params[:sort] ||= ""

    conditions = ["1=1"]
    conditions << "goods.good_type = '#{params[:good_type]}'" if params[:good_type].present? && params[:good_type] != "all"
    conditions << "goods.good_info_id = '#{params[:good_info_id].to_i}'" if params[:good_info_id].present? && params[:good_info_id] != "all"
    @goods = current_company.goods.where(conditions.join(" and "))
                                  .paginate(page: params[:page], per_page: 5)
                                  .order(params[:sort])
  end

  def get_good_list
    @sale_courses = SaleCourse.where(company_id: nil)
    @sale_courses +=  current_company.sale_courses
    @view_type = params[:view_type]

    params[:good_type] ||= "all"
    params[:good_info_id] ||= "all"
    params[:sort] ||= ""

    conditions = ["1=1"]
    conditions << "goods.good_type = '#{params[:good_type]}'" if params[:good_type].present? && params[:good_type] != "all"
    conditions << "goods.good_info_id = '#{params[:good_info_id].to_i}'" if params[:good_info_id].present? && params[:good_info_id] != "all"
    @goods = current_company.goods.where(conditions.join(" and "))
                                  .paginate(page: params[:page], per_page: 5)
                                  .order(params[:sort])
  end

  def goods_shop

    @sale_courses = SaleCourse.where(company_id: nil)
    @sale_courses +=  current_company.sale_courses

    params[:good_type] ||= "all"
    params[:good_info_id] ||= "all"
    params[:sort] ||= ""

    conditions = ["1=1"]
    conditions << "goods.status = '正常'"
    conditions << "goods.good_type = '#{params[:good_type]}'" if params[:good_type].present? && params[:good_type] != "all"
    conditions << "goods.good_info_id = '#{params[:good_info_id].to_i}'" if params[:good_info_id].present? && params[:good_info_id] != "all"
    @goods = current_company.goods.where(conditions.join(" and "))
                                  .paginate(page: params[:page], per_page: 8)
                                  .order(params[:sort])
  end

  def new

    @others = current_company.sale_courses.where(sale_type: '周边商品')
    @courses = current_company.sale_courses.where(sale_type: '课程商品')
    
    #修改默认的课程商品类型的公司id为0 flydragon
    @courses += SaleCourse.where(company_id: nil,sale_type: '课程商品')
  end

  def create
    p '===========商品============'
    p goods_params
    good = Good.new(goods_params)
    good.company_id = current_company.id
    good.save!

    p '===========折扣============'
    p discount_params
    discount_params.each do |dis|
      discount = Discount.new(dis)
      discount.good_id = good.id
      discount.save!
    end
    respond_to do |format|
      format.js { render js: "window.location.href = '/admin/goods'" }
    end
  end

  def edit
    @sale_courses = SaleCourse.where(company_id: nil)
    @sale_courses +=  current_company.sale_courses
    @discounts = @good.discounts
    @time_discounts = @discounts.where(discount_type: '时间优惠')
    @num_discounts = @discounts.where(discount_type: '数量优惠')
  end

  def update
    p '===========商品============'
    p goods_params
    @good.update!(goods_params)

    p '===========折扣============'
    p discount_params
    discounts = @good.discounts
    discounts.destroy_all

    discount_params.each do |dis|
      discount = Discount.new(dis)
      discount.good_id = @good.id
      discount.save!
    end
    respond_to do |format|
      format.js { render js: "window.location.href = '/admin/goods'" }
    end
  end

  def show
    @discounts = @good.discounts
    @time_discounts = @discounts.where(discount_type: '时间优惠')
    @num_discounts = @discounts.where(discount_type: '数量优惠')

  end

  def change_status
    if @good.status == '正常'
      @good.update!(status: '下架')
    elsif @good.status == '下架'
      @good.update!(status: '正常')
    end
    redirect_to admin_good_path
  end
  

  # 商品交易记录，kevin
  def record
    good_id = params[:id];
    @good = Good.find_by_id(good_id);
    
    @orders_array = Array.new();
    orders = Order.where(good_id: good_id);
    for order in orders
        order_hash = Hash.new();
        order_hash["time"] = DateTime.parse(order.created_at.to_s).strftime('%Y-%m-%d %H:%M').to_s;
        
        if order.student_id != 0
            order_hash["buy_name"] = Student.find_by_id(order.student_id).name;
        else
            # 意向学员和正式学员两种判断
            if PotentialStudent.find_by_id(order.potential_student_id)
                order_hash["buy_name"] = PotentialStudent.find_by_id(order.potential_student_id).name;    
            else
                order_hash["buy_name"] = Student.find_by_potential_student_id(order.potential_student_id).name;    
            end
        end
        

        order_hash["amount"] = order.amount;
        order_hash["total_price"] = order.total_price;

        order_hash["employee_name"] = Employee.find_by_id(order.employee_id).name;      
        if (order_hash["employee_name"].length == 0) || !order_hash["employee_name"]
            order_hash["employee_name"] = "缺少员工信息"  
        end  

        @orders_array.push(order_hash);
    end
    @orders_array = @orders_array.paginate(page: params[:page], per_page: 5);
  end

  def price
    arr = @good.discounts.map { |x| x.discount_percent(params[:unit].to_i) }
    percent = arr.compact.min || 100
    @price = @good.price * percent/100
    @total = @price * (params[:unit].to_i)
  end

  private
  def set_good
    @good = Good.find(params[:id])
  end

  def goods_params
    params.permit(goods: [:good_type, :good_info_id, :name, :amount, :price, :stock, :month_of_validity, :remark, :avatar])[:goods]["0"]
  end

  def discount_params
    params.permit(discount: [:discount_type, :amount, :percent, :begin_at, :end_at] )[:discount].try(:values) || []
  end

  def authorize_good
    authorize Good,:index?
  end

  def authorize_save
    authorize Good,:save?
  end


end
